<template>
  <div id="viewDiv">
    <div id="mapViewDiv">
      <div id="serchBox">
        <div>
          <input class="form-control" style="width:200px" id="serchBox" type="text" placeholder="请输入你要搜索的志愿活动" v-model="searchText" />
          <!-- <button class="btn btn-info" type="button" id="serchBtn" style="width: 50px;;height: 30px;" @click="SerchVoluntary">搜索</button> -->
        </div>
        <div>
          <ul class="search-content" v-show="serchBoxUl">
            <li class="search-item" v-for="(item,index) of serchBoxList" :key="index" @click="handleSerchClick(item.activityName)">{{ item.activityName }}</li>
            <li class="search-item" v-show="hasNoData">没有找到匹配数据</li>
          </ul>
        </div>
      </div>
      <button type="button" id="DrawRectangle" class="btn btn-info" @click="AnalyseExtent">分析区域</button>
      <button type="button" id="ShowComment" class="btn btn-primary" @click="ChangeCommentBox">{{isHideComment ? '展示评论区' : '隐藏评论区'}}</button>
      <div id="CommentBox" v-show="!isHideComment" class="alert alert-light" style="width:400px;height:400px">
        <table class="table table-striped table-hover" v-show="IsShowDetailReview">
          <tbody>
            <tr v-for="(item,index) in Reviews" :key="item.reviewID" @click="ShowDetailReview(item.reviewID)">
              <td scope="row">
                {{ index+1 }}
              </td>
              <td>
                <div>{{ item.vAandVRelationships.voluntaryModel.voluntaryName }}</div>
                <div style=" margin-top:5px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap; width: 330px;">{{ item.reviewContent }}</div>
              </td>
            </tr>
          </tbody>
        </table>
        <div v-show="!IsShowDetailReview" style="width:400px;height:400px;color: black;">
          <div>用户名：{{ DetailReview.voluntaryName }}</div>
          <div style="width: 385px;word-break:break-all; word-wrap:break-word;margin-top: 5px;">{{ DetailReview.reviewContent }}</div>
          <button style="position: absolute; left: 0px; bottom: 0px;" class="btn btn-success" @click="BackReviewList">返回</button>
        </div>
      </div>
      <div ref="AnalyseBox" v-show="isShowAnalyseBox" id="AnalyseBox" style="width:600px;height:400px;background-color: azure;">        
      </div>
      <button id="BtnAnalyse" v-show="isShowAnalyseBox" class="btn btn-warning" @click="CloseAnalyseBox">关闭分析面板</button>
      <button id="BtnGraphicClear"  class="btn btn-secondary" @click="ClearGraphic">清除所有图形</button>
    </div>
  </div>
</template>

<script>
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import SimpleRenderer from '@arcgis/core/renderers/SimpleRenderer.js'
import PictureMarkerSymbol from '@arcgis/core/symbols/PictureMarkerSymbol.js'
import PopupTemplate from '@arcgis/core/PopupTemplate.js'
import ActionButton from '@arcgis/core/support/actions/ActionButton.js'
import axios from 'axios'
import Sketch from '@arcgis/core/widgets/Sketch'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer.js'
import * as echarts from 'echarts'
import { whenOnce } from '@arcgis/core/core/watchUtils'
export default {
  name: 'VoluntaryHomePage',
  data() {
    return {
      mapview: null,
      isHideComment: true,
      searchText: '',
      VoluntaryGraphics: null,
      Reviews: null,
      ActivityID: '1111111',
      IsShowDetailReview: true,
      DetailReview: {
        voluntaryName: '',
        reviewContent: ''
      },
      serchBoxList: null,
      hasNoData: true,
      serchBoxUl: false,
      sketch: null,
      layer: null,
      analyseLayer: null,
      lastAnalyseGraphic: null,
      isShowAnalyseBox:false
    }
  },
  methods: {
    ChangeCommentBox() {
      this.isHideComment = !this.isHideComment
      this.mapview.ui.add('CommentBox', 'bottom-left')
    },
    SerchVoluntary() {
      try {
        for (let i = 0; i < this.VoluntaryGraphics.length; i++) {
          let result = this.VoluntaryGraphics[i]
          if (result.attributes.VoluntaryName.search(this.searchText) !== -1) {
            this.mapview
              .goTo({
                center: result.geometry
              })
              .then(() => {
                this.mapview.popup.open({
                  features: [result],
                  location: result.geometry.centroid
                })
                this.ActivityID = result.attributes.VoluntaryActivityID
              })
            return
          }
        }
      } catch (ex) {
        console.log(ex)
      }
    },
    ShowDetailReview(reviewID) {
      this.IsShowDetailReview = !this.IsShowDetailReview
      this.Reviews.forEach(element => {
        if (element.reviewID == reviewID) {
          this.DetailReview.voluntaryName = element.vAandVRelationships.voluntaryModel.voluntaryName
          this.DetailReview.reviewContent = element.reviewContent
          return
        }
      })
    },
    BackReviewList() {
      this.IsShowDetailReview = !this.IsShowDetailReview
    },
    handleSerchClick(name) {
      this.searchText = name
      this.serchBoxUl = false
      this.SerchVoluntary()
    },
    AnalyseExtent() {
      let component = this
      let isFirst = true
      // 激活绘制矩形的模式
      this.sketch.create('rectangle')
      // 监听绘制完成的事件
      component.sketch.on('create', async function (event) {
        if (event.state === 'complete' && isFirst) {
          isFirst = !isFirst
          if (component.lastAnalyseGraphic != null) {
            component.analyseLayer.remove(component.lastAnalyseGraphic)
          }
          component.lastAnalyseGraphic = event.graphic
          // 获取绘制的矩形几何
          const geometry = event.graphic.geometry
          // 获取要素图层视图，并返回一个 Promise
          const layerView = await component.mapview.whenLayerView(component.layer)
          let results = await layerView.queryFeatures({
            geometry: geometry,
            spatialRelationship: 'intersects'
          })
          // 获取查询的要素数组
          const features = results.features
          // 如果有查询的要素，显示它们的属性信息
          if (features.length > 0) {
            let array = []
            for (let i = 0; i < features.length; i++) {
              array[i] = features[i].attributes.VoluntaryActivityID
            }
            let result = (await component.axios.post('/Share/AnalyseActivity', { iDs: array })).data
            
            component.isShowAnalyseBox=true

            let myChart = echarts.init(component.$refs.AnalyseBox, null, {
              renderer: 'canvas',
              useDirtyRect: false
            })

            let option

            option = {
              title: {
                text: '各类型数据',
                subtext: '',
                left: 'center'
              },
              tooltip: {
                trigger: 'item'
              },
              legend: {
                orient: 'vertical',
                left: 'left'
              },
              series: [
                {
                  name: '统计数据',
                  type: 'pie',
                  radius: '50%',
                  data:[],
                  emphasis: {
                    itemStyle: {
                      shadowBlur: 10,
                      shadowOffsetX: 0,
                      shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                  }
                }
              ]
            }

            for (let i = 0; i < result.length; i++) {
              option.series[0].data[i] = { value: result[i].count, name: result[i].name }
            }

            if (option && typeof option === 'object') {
              myChart.setOption(option)
            }

            window.addEventListener('resize', myChart.resize)

            component.sketch.cancel()
          } else {
            component.sketch.cancel()
            // 如果没有查询的要素，提示用户
            alert('您没有查询到任何要素，请重新绘制矩形。')
          }
        }
      })
    },
    CloseAnalyseBox(){
      this.isShowAnalyseBox=false
    },
    ClearGraphic(){
      this.analyseLayer.removeAll()
    }
  },
  created() {
    const map = new Map({
      basemap: 'osm-streets'
    })
    const VoluntaryActivityPointSymbol = new PictureMarkerSymbol({
      url: 'https://static.arcgis.com/images/Symbols/Shapes/BlackStarLargeB.png',
      width: '26px',
      height: '26px'
    })
    const VoluntaryActivityPointRenderer = new SimpleRenderer({
      symbol: VoluntaryActivityPointSymbol
    })
    const joinActivityButton = new ActionButton({
      title: '参加志愿',
      id: 'joinButton'
    })
    let identity = localStorage.getItem('Identity')
    let voluntaryActivityPopupTemplate
    if (identity === 'Voluntary') {
      voluntaryActivityPopupTemplate = new PopupTemplate({
        title: '志愿活动详情',
        content: () => {
          return `
        <div class="esri-feature__fields esri-feature__content-element">
        <table class="esri-widget__table" summary="属性和值列表">
          <tbody>
            <tr>
              <th class="esri-feature__field-header">组织者名称</th>
              <td class="esri-feature__field-data">{OrganizationName}</td>
            </tr>
            <tr>
              <th class="esri-feature__field-header">志愿名称</th>
              <td class="esri-feature__field-data">{VoluntaryName}</td>
            </tr>
            <tr>
              <th class="esri-feature__field-header">志愿详情</th>
              <td class="esri-feature__field-data">{VoluntaryContent}</td>
            </tr>
          </tbody>
        </table>
      </div>
        `
        },
        actions: [joinActivityButton]
      })
    } else {
      voluntaryActivityPopupTemplate = new PopupTemplate({
        title: '志愿活动详情',
        content: () => {
          return `
        <div class="esri-feature__fields esri-feature__content-element">
        <table class="esri-widget__table" summary="属性和值列表">
          <tbody>
            <tr>
              <th class="esri-feature__field-header">组织者名称</th>
              <td class="esri-feature__field-data">{OrganizationName}</td>
            </tr>
            <tr>
              <th class="esri-feature__field-header">志愿名称</th>
              <td class="esri-feature__field-data">{VoluntaryName}</td>
            </tr>
            <tr>
              <th class="esri-feature__field-header">志愿详情</th>
              <td class="esri-feature__field-data">{VoluntaryContent}</td>
            </tr>
          </tbody>
        </table>
      </div>
        `
        }
      })
    }

    const layer = new FeatureLayer({
      // URL to the service
      url: 'https://services8.arcgis.com/CmXfu09loK81if9H/arcgis/rest/services/VoluntaryActivityPoint/FeatureServer/0',
      outFields: ['*'],
      popupTemplate: voluntaryActivityPopupTemplate,
      renderer: VoluntaryActivityPointRenderer
    })
    map.add(layer)
    const mapview = new MapView({
      map,
      center: [116.8, 36.55],
      zoom: 5
    })
    // Event handler that fires each time an action is clicked.
    mapview.popup.on('trigger-action', function (event) {
      if (event.action.id === 'joinButton') {
        let joinV = confirm('你确定参加此志愿吗')
        if (joinV) {
          axios
            .post('/SelectIdentity/Voluntary/JoinVoluntaryActivity', {
              activityID: mapview.popup.selectedFeature.attributes.VoluntaryActivityID,
              voluntaryID: JSON.parse(localStorage.getItem('Person')).voluntaryID
            })
            .then(res => {
              if (res.data) {
                alert('参加成功')
              } else {
                alert('已重复参加，或参加失败')
              }
            })
        }
      }
    })

    let component = this
    mapview.whenLayerView(layer).then(layerView => {
      layerView.watch('updating', value => {
        if (!value) {
          layerView
            .queryFeatures({
              geometry: mapview.extent,
              returnGeometry: true,
              orderByFields: ['OBJECTID']
            })
            .then(results => {
              component.VoluntaryGraphics = results.features
            })
        }
      })
    })
    mapview.on('click', e => {
      let query = layer.createQuery()
      query.geometry = e.mapPoint
      query.distance = 1
      query.units = 'miles'
      query.spatialRelationship = 'intersects'
      query.returnGeometry = true
      query.outFields = ['*']
      layer.queryFeatures(query).then(res => {
        try {
          component.ActivityID = res.features[0].attributes.VoluntaryActivityID
        } catch (ex) {
          console.log(ex)
        }
      })
    })

    const gLayer = new GraphicsLayer()
    map.add(gLayer)

    // 创建一个绘制组件
    const sketch = new Sketch({
      view: mapview,
      layer: gLayer,
      // visibleElements: {
      //   createTools: {
      //     point: false,
      //     polyline: false,
      //     polygon: false,
      //     circle: false
      //   }
      // },
      visible: false
    })

    this.mapview = mapview
    this.sketch = sketch
    this.layer = layer
    this.analyseLayer = gLayer
  },
  mounted() {
    this.mapview.container = 'mapViewDiv'
    //确定搜索框位置
    this.mapview.ui.add('serchBox', 'top-right')
    //确定显隐按钮位置
    this.mapview.ui.add('ShowComment', 'bottom-right')
    // //确定搜索按钮位置
    // this.mapview.ui.add('serchBtn', 'top-right')
    //确定分析区域位置
    this.mapview.ui.add('DrawRectangle', 'top-left')
    //this.mapview.ui.add(this.sketch, 'top-right')
    this.mapview.ui.add('AnalyseBox', 'bottom-left')
    this.mapview.ui.add('BtnAnalyse','top-left')
    this.mapview.ui.add('BtnGraphicClear','top-left')
  },
  watch: {
    searchText(newV, oldV) {
      if (oldV !== newV && newV !== '') {
        this.axios.get(`/Share/GetActivityByActivityName?ActivityPartName=${this.searchText}`).then(res => {
          if (res.data.length !== 0) {
            this.serchBoxList = res.data
            this.hasNoData = false
            this.serchBoxUl = true
          } else {
            this.hasNoData = true
          }
        })
      }
    },
    ActivityID(newV, oldV) {
      if (oldV !== newV && newV != '') {
        axios.get(`/Share/GetReviewByActivityID?ActivityID=${this.ActivityID}`).then(res => {
          this.Reviews = res.data
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
#viewDiv {
  padding: 0;
  margin: 0;
  height: 100%;
  width: 100%;
}
#mapViewDiv {
  padding: 0;
  margin: 0;
  height: 100%;
  width: 100%;
}
.search-content {
  overflow: hidden;
  list-style: none;
  position: absolute;
  top: 30px;
  height: 50px;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  .search-item {
    padding-left: 0.2rem;
    background: #fff;
    color: black;
  }
}
</style>
